var React = require('react');
var ReactDOM = require('react-dom');
var createReactClass = require('create-react-class');
const remote = require('electron').remote;
const {dialog} = require('electron').remote
const {clipboard} = require('electron')
const emojis = require('./emoji.js');

var InputBar = createReactClass({
    getInitialState: function() {
        return {
            showEmoji:false,
        };
    },

    showContextMenu: function(e, props) {
        e.preventDefault();
        e.stopPropagation();
        console.log("context menu event:", e);
        console.log("context menu props:", props);

        var menu;
        var enabled = (this.entry.value.length > 0);
        if (enabled) {
            menu = new remote.Menu.buildFromTemplate([
                {label: "剪切", role:"cut"},
                {label: "复制", role:"copy"},
                {label: "粘贴", role:"paste"},
            ]);
        } else {
            menu = new remote.Menu.buildFromTemplate([
                {label: "剪切", enabled:false},
                {label: "复制", enabled:false},
                {label: "粘贴", role:"paste"},
            ]);
        }

        menu.popup({window:remote.getCurrentWindow()});
    },

    renderEmoji: function() {
        var self = this;
        var arr = emojis.map((e, index) => {
            function onEmojiClick() {
                console.log("emoji click:", e.name, e.value);
                self.entry.value = self.entry.value + e.value;
                self.entry.focus();
            }

            return (
                <div key={index}>
                    <span>
                        <span onClick={onEmojiClick}
                              className="emoji">{e.value}</span>
                    </span>
                </div>
            );
        });

        return (
            <div className="expressionWrap">
                <i className="arrow"></i>
                {arr}
            </div>
        );
    },

    onImage: function(e) {
        var filters = [{name: 'Images', extensions: ['jpg', 'jpeg', 'png']}];
        var options = {
            properties:['openFile'],
            filters:filters
        };


        var self = this;
        var win = remote.getCurrentWindow()
        dialog.showOpenDialog(win, options,
                              function(filePath) {
                                  console.log("image file path:", filePath);
                                  if (filePath && filePath.length > 0) {
                                      self.props.onImageChange(filePath[0]);
                                  }
                              });
    },

    onFile: function() {
        var options = {
            properties:['openFile'],
        };

        var self = this;
        var win = remote.getCurrentWindow()
        dialog.showOpenDialog(win, options,
                              function(filePath) {
                                  console.log("file path:", filePath);
                                  if (filePath && filePath.length > 0) {
                                      self.props.onFileChange(filePath[0]);
                                  }
                              });
    },

    onEmoji: function(e) {
        var showEmoji = !this.state.showEmoji;
        this.setState({
            showEmoji:showEmoji
        });

        e.stopPropagation();
        e.nativeEvent.stopImmediatePropagation();
    },

    onAudio: function(e) {
        console.log("on audio...");
        this.props.onAudioVOIP();
    },

    onVideo: function(e) {
        console.log("on video...");
        this.props.onVideoVOIP();
    },

    hideEmoji: function() {
        this.setState({
            showEmoji:false
        });
    },

    onKeyPress:function(e) {
        if (e.ctrlKey && e.key == 'Enter') {
            this.entry.value = this.entry.value + "\n";
            return;
        }
        if (e.key != 'Enter') return;

        var value = this.entry.value;
        var msg = value.trim();
        if (!util.isBlank(msg)) {
            this.props.sendTextMessage(msg);
        }
        return false;
    },

    onPaste: function(e) {
        //https://github.com/electron/electron/issues/9035
        console.log("on paste event:", e);
        var filePath;
        if (process.platform == 'darwin') {
            filePath = clipboard.read('public.file-url').replace('file://', '');
        } else {
            //windows
            var rawFilePath = clipboard.read('FileNameW');
            filePath = rawFilePath.replace(new RegExp(String.fromCharCode(0), 'g'), '');
        }
        if (filePath) {
            e.preventDefault();
            console.log("filepath:", filePath);
            this.props.onFileChange(filePath);
        } else {
            var item = e.clipboardData.items[0];
            console.log("on paste item:", item);
            if (item.kind == "file" && item.type.startsWith("image/")) {
                e.preventDefault();
                var blob = item.getAsFile();
                this.props.onImageChange(undefined, blob);
            }
        }
    },

    clear: function() {
        this.entry.value = "";
    },

    render: function() {
        var hideAudioVOIP = this.props.hideAudioVOIP;
        var hideVideoVOIP = this.props.hideVideoVOIP;
        var hideEmoji = (process.platform != 'darwin');
        return (
            <div className="chat-form pane-chat-footer">
                <div id="MessageForm" className="">
                    <div id="MessageForm-header">
                        <div className={hideEmoji ? "MessageForm-tool hide" : "MessageForm-tool"}>
                            <i onClick={this.onEmoji}
                               className="iconfont-smile"></i>
                            {this.state.showEmoji ? this.renderEmoji() : null}
                        </div>
                        <div className="MessageForm-tool">
                            <i className="screen_shot"
                               id="screen_shot"
                               style={{
                                   position: 'relative',
                                   "zIndex": 1
                               }}
                               onClick={this.props.onClipboard}></i>
                        </div>
                        <div className="MessageForm-tool">
                            <i className="iconfont-upload"
                               id="upload-image"
                              onClick={this.onImage}
                               style={{
                                   position: 'relative',
                                   "zIndex": 1
                               }}>
                            </i>
                        </div>
                        <div className="MessageForm-tool">
                            <i className="file_shot"
                               id="upload-file"
                               onClick={this.onFile}
                               style={{
                                   position: 'relative',
                                   "zIndex": 1}}>
                            </i>
                        </div>

                        {/* <div className={hideVideoVOIP ? "MessageForm-tool hide right" : "MessageForm-tool right"}>
                            <i className="voip_video"
                               onClick={this.onVideo}
                               style={{
                                   position: 'relative',
                                   "zIndex": 1}}>
                            </i>
                        </div>

                        <div className={hideAudioVOIP ? "MessageForm-tool hide right" : "MessageForm-tool right"}>
                            <i className="voip_audio"
                               onClick={this.onAudio}
                               style={{
                                   position: 'relative',
                                   "zIndex": 1}}>
                            </i>
                        </div> */}
                    </div>
                </div>
                <textarea id="entry"
                        onContextMenu={this.showContextMenu}
                        onPaste = {this.onPaste}
                        ref={(e) => {this.entry=e;}}
                        onKeyPress={this.onKeyPress}
                        className="chat-input"></textarea>
            </div>
        );
    },


});

module.exports = InputBar;
